package tasoloikka;

import java.awt.Color;
import java.awt.Graphics;
import java.io.File;
import java.io.PrintWriter;

//64 x 40 Tileä mahtuu 1024x640 tilaan
public class Map {

  private ActionListener actionListener;
  private int mapWidth;
  private int mapHeight;
  private String mapName;
  private Tile[][] loadingMap;
  //MapEditor muuttujat
  private boolean mapEditorEnabled = false;
  private int selectedBlock = 1;

  public Map(int w, int h, String mN, ActionListener actionListener) {
    this.actionListener = actionListener;
    this.mapWidth = w;
    this.mapHeight = h;
    this.mapName = mN;
    loadingMap = MapLoader.CreateMap(mapWidth, mapHeight, mapName);
  }

  public void paint(Graphics gbi) {
    for (int i = 0; i < mapWidth; i++) {
      for (int j = 0; j < mapHeight; j++) {
        if (loadingMap[i][j] != null) {
          loadingMap[i][j].paint(gbi, i, j);
        }
      }
    }

    gbi.setColor(Color.white);
    gbi.drawString("MapEditor " + mapEditorEnabled + " Selected(" + selectedBlock + ")", 10, 55);
  }

  public Tile[][] getMap() {
    return loadingMap;
  }

  public void saveMap() {

    try {
      PrintWriter writer = new PrintWriter(new File("Resources//Maps//" + mapName + ".txt"));

      for (int i = 0; i < mapHeight; i++) {
        for (int j = 0; j < mapWidth; j++) {
          if (loadingMap[j][i] != null) {
            writer.println(loadingMap[j][i].getSaveInfo());
          } else {
            writer.println("null");
          }
          
        }
      }

      writer.close();

    } catch (Exception ex) {
      ex.printStackTrace();
    }

  }

  //Getterit
  //Getterit
  //Getterit
  public boolean getMapEditorEnabled() {
    return mapEditorEnabled;
  }

  //MapeditorCode
  public void mapEditor() {
    mapEditorEnabled = true;

  }

  public void nextBlock(boolean x) {
    if (x) {
      selectedBlock++;
    } else {
      selectedBlock--;
    }
  }

  public void changeBlock() {
    int blockSize = 16;
    if (selectedBlock == 0) {
      loadingMap[actionListener.mouseX / blockSize][actionListener.mouseY / blockSize] = new Tile((actionListener.mouseX/blockSize)*blockSize, (actionListener.mouseY/blockSize)*blockSize, blockSize, blockSize, "blue", "kikkare", false);
    } else if (selectedBlock == 1) {
      loadingMap[actionListener.mouseX / blockSize][actionListener.mouseY / blockSize] = new Tile((actionListener.mouseX/blockSize)*blockSize, (actionListener.mouseY/blockSize)*blockSize, blockSize, blockSize, "red", "kuutio", true);
    } else if (selectedBlock == 2) {
      loadingMap[actionListener.mouseX / blockSize][actionListener.mouseY / blockSize] = null;
    }


  }
}
